﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace Common
{
   public class FileOperation
    {
        /// <summary>
        /// 删除文件
        /// </summary>
        /// <returns></returns>
        public static void DropToFile(string fileName)
        {
            if (!File.Exists(fileName))
            {

            }
            else
            {
                File.Delete(fileName);
            }
        }


        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static bool DownLoadToFile(string filePath)
        {
            try
            {
                HttpContext.Current.Response.ClearHeaders();
                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.Expires = 0;
                HttpContext.Current.Response.Buffer = true;
                HttpContext.Current.Response.AddHeader("Accept-Language", "zh-tw");
                string name = System.IO.Path.GetFileName(filePath);
                System.IO.FileStream files = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
                byte[] byteFile = null;
                if (files.Length == 0)
                {
                    byteFile = new byte[1];
                }
                else
                {
                    byteFile = new byte[files.Length];
                }
                files.Read(byteFile, 0, (int)byteFile.Length);
                files.Close();
                HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(name, System.Text.Encoding.UTF8));
                HttpContext.Current.Response.ContentType = "application/octet-stream;charset=gbk";
                HttpContext.Current.Response.BinaryWrite(byteFile);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
}
